package com.giaothong;
import java.util.Collection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.giaothong.entities.Question;
import com.giaothong.view.AnimationHelper;
import com.giaothong.view.QuestionView;



public class HocTracNghiemActivity extends Activity implements OnClickListener, OnSeekBarChangeListener{
	
	private Button btn_back, btn_setting, btn_checkmard, btn_next, btn_pre;
	private SeekBar seekbar;
	private ViewFlipper flipper;
	private Collection<Question> listQuestion;
	private Context context;
	private int topicID;
	private Question questionCheckIsMark;
	private int sizeListQuestion;
	private ScrollView[] scrollview;
	private ProgressDialog mProgressDialog = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_hoctracnghiem);
		
		context = this.getApplicationContext();
		unit();
		
		Bundle intent = getIntent().getExtras();
		topicID =  intent.getInt("topic_id");
		listQuestion = Main.getQuestionDAL().getQuestionsByTopic(topicID);
		sizeListQuestion = HocTracNghiemActivity.this.listQuestion.size();
		scrollview = new ScrollView[sizeListQuestion];
		
		new AsyncLoadFlipper().execute(context);
		seekbar.setMax(flipper.getChildCount());
		
		//show question voi index duoc save tu Pref
		showQuestionFromIdSharedPreferences();
		
		if(this.getQuestionCurrentOnFlipper().getIsMark() >=0)
		
		//update trang thai button checkmark
		upDateStatusButtonMark(this.getQuestionCurrentOnFlipper().getIsMark());
	}

	private void unit(){
		btn_back = (Button)findViewById(R.id.hoctracnghiem_btnBack);
		btn_setting = (Button)findViewById(R.id.hoctracnghiem_btnSetting);
		btn_checkmard = (Button)findViewById(R.id.hoctracnghiem_btnCheckmark);
		btn_next = (Button)findViewById(R.id.hoctracnghiem_btnNext);
		btn_pre = (Button)findViewById(R.id.hoctracnghiem_btnPrevious);
		flipper = (ViewFlipper)findViewById(R.id.hoctracnghiem_flipper);
		seekbar = (SeekBar)findViewById(R.id.seekbar);
		
		
		btn_back.setOnClickListener(this);
		btn_setting.setOnClickListener(this);
		btn_checkmard.setOnClickListener(this);
		btn_next.setOnClickListener(this);
		btn_pre.setOnClickListener(this);
		
		seekbar.setOnSeekBarChangeListener(this);
	}
	
	private void upDateStatusButtonMark(int flag){
		if(flag == 0){
			btn_checkmard.setText(R.string.hocTN_danhDau);
			
		}else{
			btn_checkmard.setText(R.string.hocTN_boDanhDau);
		}
	}
	/*	Ham tra ve Question hien trong Flipper dang hien thi.
	 * 
	 */
	private Question getQuestionCurrentOnFlipper(){
		Question questionCurrent = null;
		int idFlipperCurrent = flipper.getDisplayedChild();
		int indexQues = 0;
		for(Question ques : listQuestion){
				if(indexQues == idFlipperCurrent){
					questionCurrent = ques;
					break;
				}
			indexQues ++;
		}
		return questionCurrent;
	}
	
	private void storeIdQuestionCurrentToSharedPreferences(){
		switch(topicID){
		//luu index Childe of filpper
			case 1:{
				Main.getHistoryStudyDAL().setHistoryStudyMoto(flipper.getDisplayedChild());
				break;
			}
			case 2:{
				Main.getHistoryStudyDAL().setHistoryStudyOto(flipper.getDisplayedChild());
				break;
			}
			case 3:{
				Main.getHistoryStudyDAL().setHistoryStudyBienBao(flipper.getDisplayedChild());
				break;
			}
			case 4:{
				Main.getHistoryStudyDAL().setHistoryStudySaHinh(flipper.getDisplayedChild());
				break;
			}
			case 5:{
				Main.getHistoryStudyDAL().setHistoryStudyQuestionMarked(flipper.getDisplayedChild());
				break;
			}
		}
	}
	private void showQuestionFromIdSharedPreferences(){
		switch(topicID){
		//luu index Childe of filpper
			case 1:{
				flipper.setDisplayedChild(Main.getHistoryStudyDAL().gettHistoryStudyMoto());
				seekbar.setProgress(Main.getHistoryStudyDAL().gettHistoryStudyMoto());
				break;
			}
			case 2:{
				flipper.setDisplayedChild(Main.getHistoryStudyDAL().gettHistoryStudyOto());
				seekbar.setProgress(Main.getHistoryStudyDAL().gettHistoryStudyMoto());
				break;
			}
			case 3:{
				flipper.setDisplayedChild(Main.getHistoryStudyDAL().gettHistoryStudyBienBao());
				seekbar.setProgress(Main.getHistoryStudyDAL().gettHistoryStudyMoto());
				break;
			}
			case 4:{
				flipper.setDisplayedChild(Main.getHistoryStudyDAL().gettHistoryStudySaHinh());
				seekbar.setProgress(Main.getHistoryStudyDAL().gettHistoryStudyMoto());
				break;
			}
			case 5:{
				flipper.setDisplayedChild(Main.getHistoryStudyDAL().gettHistoryStudyQuestionMarked());
				seekbar.setProgress(Main.getHistoryStudyDAL().gettHistoryStudyMoto());
				break;
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
			case R.id.hoctracnghiem_btnBack: 
			{
				//luu id question hien hanh vao pre
				storeIdQuestionCurrentToSharedPreferences();
				 
				
				listQuestion.clear();
				flipper.removeAllViews();
				flipper.destroyDrawingCache();
				Intent intent = new Intent(getApplicationContext(), HomeTabActivity.class);
				startActivity(intent);
				HocTracNghiemActivity.this.finish();
				break;	
			}
			case R.id.hoctracnghiem_btnSetting:
				break;
			case R.id.hoctracnghiem_btnCheckmark:{
				//Log.i("Mark Question ","Mard = "+questionMark.getIsMark());
				questionCheckIsMark = this.getQuestionCurrentOnFlipper(); // lay question hien tai
				
				//thay doi gia tri map khi nhan button checkmar
				if(questionCheckIsMark.getIsMark() == 0)
					questionCheckIsMark.setIsMark(1);
				else 
					questionCheckIsMark.setIsMark(0);
				
				Main.getQuestionDAL().update(questionCheckIsMark);       // update question mark vao db
				upDateStatusButtonMark(questionCheckIsMark.getIsMark()); // update lai trang thai button mark
				break;
			}
			case R.id.hoctracnghiem_btnNext:{
				flipperNext();
				
				break;
			}
			case R.id.hoctracnghiem_btnPrevious:{
				flipperPrevious();
				
				break;
			}
			case R.id.seekbar:{
				Log.i("HocTN - seekbarOnClick ", "true");
				break;
			}
		}
		
	}
	/*
	 * onTount
	 */
	private void flipperNext() {
		flipper.setInAnimation(AnimationHelper.inFromRightAnimation());
		flipper.setOutAnimation(AnimationHelper.outToLeftAnimation());
		flipper.showNext();
		seekbar.setProgress(flipper.getDisplayedChild());
		upDateStatusButtonMark(this.getQuestionCurrentOnFlipper().getIsMark());
	}

	private void flipperPrevious() {
		flipper.setInAnimation(AnimationHelper.inFromLeftAnimation());
		flipper.setOutAnimation(AnimationHelper.outToRightAnimation());
		flipper.showPrevious();
		seekbar.setProgress(flipper.getDisplayedChild());
		upDateStatusButtonMark(this.getQuestionCurrentOnFlipper().getIsMark());
	}

	SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			float sensitvity = 50;
			if ((e1.getX() - e2.getX()) > sensitvity) {
				flipperNext();

			} else if ((e2.getX() - e1.getX()) > sensitvity) {
				flipperPrevious();
			}
			return true;
		}
	};
	GestureDetector gestureDetector = new GestureDetector(simpleOnGestureListener);

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
			return gestureDetector.onTouchEvent(event);
	}
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
		// TODO Auto-generated method stub
		if(fromUser){
				flipper.setDisplayedChild(progress);
				Toast msg = Toast.makeText(this, progress + "", Toast.LENGTH_SHORT);
				msg.setGravity(Gravity.BOTTOM, msg.getXOffset()/2,msg.getYOffset()/2);
				msg.show();
		}	
			
		
		
	}
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}



//	private int sizeListQuestion;
//	public ScrollView[] scrollview;
//	private ProgressDialog mProgressDialog = null;
public class AsyncLoadFlipper extends AsyncTask<Context, Integer , Integer> {
		
	@Override
    protected void onPreExecute() {
        // TODO Khoi tao
        super.onPreExecute();
        
        mProgressDialog = new ProgressDialog(HocTracNghiemActivity.this);
        mProgressDialog.setTitle(getResources().getString(R.string.home_tab_on_trac_nghiem));
        mProgressDialog.setMessage(getResources().getString(R.string.msg_load_question));
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(HocTracNghiemActivity.this.sizeListQuestion);
        mProgressDialog.show();
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
               
            }
        });
    } 
		@Override
		protected Integer doInBackground(Context... params) {
			Log.i("sizeListQuestion", ""+sizeListQuestion);
			
			flipper.removeAllViews();
			int index = 0;
			for (Question question : HocTracNghiemActivity.this.listQuestion) {
				HocTracNghiemActivity.this.scrollview[index] = new ScrollView(HocTracNghiemActivity.this.context);
				HocTracNghiemActivity.this.scrollview[index].addView(new QuestionView(HocTracNghiemActivity.this.context,question, true));
				//flipper.addView(scrollview);
				publishProgress(index);
				index ++;
			}
			
			return index;
		}

		@Override
		protected void onPostExecute(Integer  result) {
			for(int i = 0; i < HocTracNghiemActivity.this.sizeListQuestion; i++){
				HocTracNghiemActivity.this.flipper.addView(HocTracNghiemActivity.this.scrollview[i]);
			}
			HocTracNghiemActivity.this.scrollview = null;
			mProgressDialog.dismiss(); 
		}
		protected void onProgressUpdate(Integer... progress) {
			// on UI thread!
			 mProgressDialog.setProgress(progress[0]); 
		}

	
	}

}
